<script lang="ts" setup>
  import type { CmsAuthor } from '@/types/cms';
  import { onMounted, ref } from 'vue';
  import { Form, Message } from '@arco-design/web-vue';
  import { createAuthor, updateAuthor } from '@/api/cms';

  const props = defineProps<{
    author?: CmsAuthor;
  }>();

  const emit = defineEmits(['close']);

  const data = ref<Partial<CmsAuthor>>({});
  onMounted(() => {
    if (props.author) {
      data.value.authorName = props.author.authorName;
    }
  });

  const saving = ref(false);
  const formRef = ref<InstanceType<typeof Form> | null>(null);
  const handleSubmit = async () => {
    if (formRef.value) {
      const validateResult = await formRef.value.validate();
      if (!validateResult) {
        saving.value = true;
        try {
          if (props.author) {
            await updateAuthor({
              ...props.author,
              ...data.value,
            });
            Message.success('修改成功');
            emit('close', true);
          } else {
            await createAuthor(data.value);
            Message.success('添加成功');
            emit('close', true);
          }
        } finally {
          saving.value = false;
        }
      }
    }
  };
</script>

<template>
  <a-modal
    :title="author ? '修改作者' : '添加作者'"
    :width="500"
    visible
    :ok-loading="saving"
    @cancel="emit('close', false)"
    @before-ok="handleSubmit"
  >
    <div style="padding: 20px">
      <a-form ref="formRef" :model="data" layout="vertical">
        <a-form-item
          label="作者名称"
          field="authorName"
          :rules="[{ required: true, message: '不能为空' }]"
        >
          <a-input v-model="data.authorName" />
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>
